<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/31
 * Time: 9:39
 */

namespace app\index\controller;


use think\Request;

class Coupon extends Backend
{
    /**
     * 联系地址
     */
    public function index(){
        $data=Request::instance()->get();
        $da=db('coupon')
            ->join('province p', 'coupon.province_id=p.province_id','left')
            ->join('city c', 'coupon.city_id=c.city_id','left')
            ->join('county u', 'coupon.county_id=u.county_id','left');
        if (isset($data['customers_id']) && $data['customers_id'] != '') {
            $title = db('customers')->where(['username' => ['like', "%{$data['customers_id']}%"]])->field('customers_id')->select();

            $s=arr_to_str($title);
            $da->where(['coupon.customers_id' => ['in', $s]]);
        };
        $data=$da->paginate(25)
            ->each(function($item, $key){
                $item['customer']=db('customers')->where('customers_id',$item['customers_id'])->value('username');
                return $item;
            });

        return $this->fetch('index',['data'=>$data]);
    }


    /**
     * @return array|mixed|string
     * 编辑
     */
    public function edit($coupon_id = 0)
    {
        if ($data = Request::instance()->post()) {

            $user = [
                'name' => $data['name'],
                'phone' => $data['phone'],
                'province_id' => $data['province_id'],//省
                'city_id' => $data['city_id'],//市
                'county_id' => $data['county_id'],//区
                'addres'=>$data['addres'],//地址
                'addres1'=>$data['addres1'],//地址

            ];

            $res = db('coupon')->where(['coupon_id' => $data['coupon_id']])->update($user);
            if ($res === false) {
                return json_data([], 300, '编辑失败');
            }
            return json_data([], 200, '编辑成功');
        }

        if (!$coupon_id) {
            $this->error('请刷新后重试');
        }
        $res = db('coupon')
            ->join('province p', 'coupon.province_id=p.province_id','left')
            ->join('city c', 'coupon.city_id=c.city_id','left')
            ->join('county u', 'coupon.county_id=u.county_id','left')
            ->where(['coupon_id' => $coupon_id])
            ->find();

        return $this->fetch('edit', ['data' => $res]);
    }
    /**
     * 取消
     */
    public function del()
    {
        $store_id = Request::instance()->post();

        $res = false;
        if ($store_id) {
            $res = db('coupon')->where(['coupon_id' => $store_id['coupon_id']])->delete();
        }
        if ($res !== false) {
            return json_data([], 200, '删除成功');
        }
        return json_data([], 300, '删除失败');
    }



}